package com.haidechizi.fastadmin.modules.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.haidechizi.fastadmin.common.page.PageDto;
import com.haidechizi.fastadmin.common.utils.PageInfo;
import com.haidechizi.fastadmin.modules.sys.dao.SysDictDao;
import com.haidechizi.fastadmin.modules.sys.entity.SysDict;
import com.haidechizi.fastadmin.modules.sys.service.SysDictService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictDao, SysDict> implements SysDictService {

    @Override
    public PageInfo queryPage(PageDto pageDto, SysDict sysDict) {
        Wrapper<SysDict> wrapper;
        String description = sysDict.getDescription();
        Page<SysDict> page = this.selectPage(
                pageDto.cover2Page(),
                wrapper = new EntityWrapper<SysDict>()
                        .like(StringUtils.isNotBlank(description), "description", description)
        );
        int count = super.selectCount(wrapper);
        page.setTotal(count);
        return new PageInfo(page);
    }

    /**
     * 根据类型获取字典
     *
     * @param type
     * @return
     */
    @Override
    public List<SysDict> queryDictByType(String type) {
        return super.selectList(new EntityWrapper<SysDict>().eq("type", type));
    }

    /**
     * 根据类型获取字典Map
     *
     * @param type
     * @return
     */
    @Override
    public Map<String, String> queryDictMapByType(String type) {
        List<SysDict> dictList = super.selectList(new EntityWrapper<SysDict>().eq("type", type));
        return dictList.stream().collect(Collectors.toMap(SysDict::getValue, SysDict::getLabel));
    }

    /**
     * 将字典value数组转成labels
     *
     * @param values
     * @param type
     * @return
     */
    @Override
    public String coverList2Labels(String values, String type) {
        if (StringUtils.isBlank(values)) {
            return null;
        }
        String[] dictValues = StringUtils.split(values, ",");
        Map<String, String> dictMap = this.queryDictMapByType(type);
        List<String> labelList = new ArrayList<>();
        for (String value : dictValues) {
            labelList.add(dictMap.get(value));
        }
        return StringUtils.join(labelList, ",");
    }


}
